package com.课上案例练习.线程.线程安全.解决线程死锁;

import java.util.concurrent.locks.ReentrantLock;

/**
 * try Lock 获取锁失败后，不会继续等待，直接返回fasle，不会遇到阻塞等到
 * 与synchronized锁的区别
 */
public class Test1 {
    //实例化Lock对象
    //定义一把锁
    ReentrantLock lockA = new ReentrantLock();
    //定义另一把锁
    ReentrantLock lockB = new ReentrantLock();

    public static void main(String[] args) {
        Test1 test2 = new Test1();
        new Thread(new Runnable() {
            @Override
            public void run() {
                test2.run(Thread.currentThread());
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                test2.run(Thread.currentThread());
            }
        }).start();
    }

    public void run(Thread t) {
        //调用lock对象尝试获取锁，如果获取锁成功，则执行代码，如果获取锁失败，则无需等待直接返回
        if (lockA.tryLock()) {
            System.out.println("当前线程" + t.getName() + "获取锁A成功");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (lockB.tryLock()) {
                System.out.println("当前线程" + t.getName() + "获取锁B成功");
                lockB.unlock();
            }
            else{
                System.out.println(lockB.tryLock());
//                lockA.unlock();
            }




            }

        else if (lockB.tryLock()) {
            System.out.println("当前线程" + t.getName() + "获取锁B成功");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (lockA.tryLock()) {
                System.out.println("当前线程" + t.getName() + "获取锁A成功");
                lockA.unlock();
            }
            else
            {
                System.out.println(lockA.tryLock());
//                lockB.unlock();
            }




        }



    }
    }

